package com.tdam2011.grupo02.ui;

import java.util.LinkedList;

import com.tdam2011.grupo02.R;
import com.tdam2011.grupo02.compatibility.ActionBarFragmentActivity;
import com.tdam2011.grupo02.data.LogsController;
import com.tdam2011.grupo02.domain.SMS;
import com.tdam2011.grupo02.widget.popup.ActionItem;
import com.tdam2011.grupo02.widget.popup.QuickAction;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;

public class SmsConversationActivity extends ActionBarFragmentActivity
		implements OnClickDialogFragmentInterface {

	private ListView lv;
	private SmsConversationAdapter adapter;
	private String threadId;
	private String nombre;
	private String numero;
	private Uri imgUri;
	private QuickAction smsPopup;
	private TextView txtvNombre;
	private LinearLayout lySmsEdit;
	private EditText txtSms;
	private ImageButton imgbtnEdit;
	private Button btnSend;
	private Button btnCancel;
	private int positionAdapter;
	private SmsConversationAsyncTask smsConversationAsyncTask;
	private LogsController controller;
	private SMS sms;

	public static int SMS_TYPE_OTHER = 1;
	public static int SMS_TYPE_USER = 2;

	private static final int POPUP_ACTION_ITEM_SEND = 11;
	private static final int POPUP_ACTION_ITEM_DELETE = 13;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.selected_msg_conversation);

		createSmsPopup();
		Bundle data = getIntent().getExtras();
		threadId = data.getString("threadId");
		nombre = data.getString("name");
		numero = data.getString("number");
		imgUri = (Uri) data.get("imgUri");

		setTitle(nombre);
	
		adapter = new SmsConversationAdapter();
		lv = (ListView) findViewById(R.id.listMsg);
		lv.setAdapter(adapter);
		lv.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				positionAdapter = position;

				int firstPosition = lv.getFirstVisiblePosition()
						- lv.getHeaderViewsCount();
				int wantedChild = positionAdapter - firstPosition;

				View v = (View) lv.getChildAt(wantedChild);

				smsPopup.show(v);
				return false;
			}
		});

		controller = new LogsController(this);
	}

	@Override
	protected void onResume() {
		initData();
		super.onResume();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.options_menu_msgw_conversation, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
		case R.id.menu_msgw_conversation_edit:
			editSMS();
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private void initData() {
		smsConversationAsyncTask = new SmsConversationAsyncTask();
		smsConversationAsyncTask.execute(threadId);
	}

	private class SmsConversationAsyncTask extends
			AsyncTask<String, String, LinkedList<SMS>> {

		@Override
		protected LinkedList<SMS> doInBackground(String... params) {

			return controller.loadConversationSms(params[0]);
		}

		@Override
		protected void onPostExecute(LinkedList<SMS> result) {
			adapter.add(result);
			adapter.notifyDataSetChanged();
			super.onPostExecute(result);
		}
	}

	class SmsConversationAdapter extends BaseAdapter {
		private LinkedList<SMS> sms;
		private LayoutInflater inflater;

		public SmsConversationAdapter() {
			this.sms = new LinkedList<SMS>();
			inflater = LayoutInflater.from(SmsConversationActivity.this);
		}

		public void add(LinkedList<SMS> sms) {
			this.sms = new LinkedList<SMS>();
			this.sms = sms;
		}

		@Override
		public int getCount() {
			return sms.size();
		}

		@Override
		public Object getItem(int position) {
			return sms.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			Holder holder;
			final SMS info = (SMS) getItem(position);

			if (convertView == null) {

				holder = new Holder();

				holder.type = info.getType();

				if (info.getType() == 1)
					convertView = inflater.inflate(
							R.layout.item_conversation_sms_in, null);
				else
					convertView = inflater.inflate(
							R.layout.item_conversation_sms_out, null);

				holder.fecha = (TextView) convertView.findViewById(R.id.sFecha);
				holder.mensaje = (TextView) convertView
						.findViewById(R.id.sMensaje);

				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
				if (holder.type != info.getType()) {

					if (info.getType() == 1)
						convertView = inflater.inflate(
								R.layout.item_conversation_sms_in, null);
					else
						convertView = inflater.inflate(
								R.layout.item_conversation_sms_out, null);

					holder = new Holder();

					holder.fecha = (TextView) convertView
							.findViewById(R.id.sFecha);
					holder.mensaje = (TextView) convertView
							.findViewById(R.id.sMensaje);

					convertView.setTag(holder);
				}
			}

			holder.fecha.setText(info.getFecha().toLocaleString());
			holder.mensaje.setText(info.getMensaje());

			return convertView;
		}

		class Holder {
			private TextView fecha;
			private TextView mensaje;
			private int type;
		}
	}

	public void createSmsPopup() {
		ActionItem enviarItem = new ActionItem(POPUP_ACTION_ITEM_SEND,
				getString(R.string.actionSend), getResources().getDrawable(
						android.R.drawable.ic_menu_send));
		ActionItem eliminarItem = new ActionItem(POPUP_ACTION_ITEM_DELETE,
				getString(R.string.actionDelete), getResources().getDrawable(
						android.R.drawable.ic_menu_delete));

		smsPopup = new QuickAction(this);

		smsPopup.addActionItem(enviarItem);
		smsPopup.addActionItem(eliminarItem);

		smsPopup.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			@Override
			public void onItemClick(QuickAction quickAction, int pos,
					int actionId) {
				sms = (SMS) adapter.getItem(positionAdapter);

				switch (actionId) {
				case POPUP_ACTION_ITEM_SEND:
					ContactActionControllerSingleton
							.getInstance(SmsConversationActivity.this)
							.getContactActionController()
							.sendSMS(sms.getNumero(), sms.getMensaje());
					break;

				case POPUP_ACTION_ITEM_DELETE:
					showDialog();
					break;
				}
			}
		});

		smsPopup.setOnDismissListener(new QuickAction.OnDismissListener() {
			@Override
			public void onDismiss() {
			}
		});

	}

	private void editSMS() {
		if (lySmsEdit == null) {
			lySmsEdit = (LinearLayout) findViewById(R.id.lyMsgEdit);
			txtSms = (EditText) findViewById(R.id.txtMsgContent);
			btnSend = (Button) findViewById(R.id.btnMsgSend);
			btnCancel = (Button) findViewById(R.id.btnMsgCancel);

			btnSend.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					ContactActionControllerSingleton
							.getInstance(SmsConversationActivity.this)
							.getContactActionController()
							.sendSMS(numero, txtSms.getText().toString());
				}
			});

			btnCancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					lySmsEdit.setVisibility(View.GONE);
				}
			});
		}

		if (lySmsEdit.getVisibility() == View.GONE)
			lySmsEdit.setVisibility(View.VISIBLE);
		else
			lySmsEdit.setVisibility(View.GONE);
	}

	// Dialog Fragment

	private void showDialog() {
		DialogFragment newFragment = MyAlertDialogFragment.newInstance(this,
				getString(R.string.attentionAlertDialogTitle),
				getString(R.string.deleteItemAlertDialogMessage));
		newFragment.show(getSupportFragmentManager(), "dialog");
	}

	@Override
	public void doPositiveClick() {
		sms.setNombre(nombre);
		int num = controller.deleteSmsLog(sms);
		if (num != 0)
			initData();
	}

	@Override
	public void doNegativeClick() {
	}
}
